package ink.onei.shopping.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import ink.onei.shopping.domain.Detail;
import ink.onei.shopping.domain.Order;
import ink.onei.shopping.mapper.GoodsMapper;
import ink.onei.shopping.mapper.OrderMapper;
import ink.onei.shopping.service.IDetailService;
import ink.onei.shopping.service.IGoodsService;
import ink.onei.shopping.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 订单Service业务层处理
 *
 * @author nekotako
 * @date 2024-02-24
 */
@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private IDetailService detailService;


    /**
     * 查询订单
     *
     * @param orderId 订单主键
     * @return 订单
     */
    @Override
    public Order selectOrderByOrderId(Long orderId) {
        Order order = orderMapper.selectOrderByOrderId(orderId);
        String detailName = detailService.selectDetailByDetailId(order.getDetailId()).getDetailName();
        order.setDetailName(detailName);
        return order;
    }

    /**
     * 查询订单列表
     *
     * @param order 订单
     * @return 订单
     */
    @Override
    public List<Order> selectOrderList(Order order) {
        return orderMapper.selectOrderList(order);
    }

    /**
     * 新增订单
     *
     * @param order 订单
     * @return 结果
     */
    @Override
    public int insertOrder(Order order) {
        Double detailPrice = detailService.selectDetailByDetailId(order.getDetailId()).getDetailPrice();
        double totalAmount = detailPrice * order.getDetailNum();
        order.setTotalAmount(totalAmount);
        long threeSnow = IdUtil.getSnowflakeNextId();
        order.setTraceNo(String.valueOf(threeSnow));
        order.setCreateDate(new Date());
        int i = orderMapper.insertOrder(order);
        return i != 0 ? order.getOrderId().intValue() : i;
    }

    /**
     * 修改订单
     *
     * @param order 订单
     * @return 结果
     */
    @Override
    public int updateOrder(Order order) {
        return orderMapper.updateOrder(order);
    }

    /**
     * 批量删除订单
     *
     * @param orderIds 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteOrderByOrderIds(Long[] orderIds) {
        return orderMapper.deleteOrderByOrderIds(orderIds);
    }

    /**
     * 删除订单信息
     *
     * @param orderId 订单主键
     * @return 结果
     */
    @Override
    public int deleteOrderByOrderId(Long orderId) {
        return orderMapper.deleteOrderByOrderId(orderId);
    }
}
